﻿'
' Will Strohl (wills@strohlsitedesign.com)
' http://www.willstrohl.com
'
'Copyright (c) 2010, Will Strohl
'All rights reserved.
'
'Redistribution and use in source and binary forms, with or without modification, are 
'permitted provided that the following conditions are met:
'
'Redistributions of source code must retain the above copyright notice, this list of 
'conditions and the following disclaimer.
'
'Redistributions in binary form must reproduce the above copyright notice, this list 
'of conditions and the following disclaimer in the documentation and/or other 
'materials provided with the distribution.
'
'Neither the name of StrohlSiteDesign.com nor the names of its contributors may be 
'used to endorse or promote products derived from this software without specific prior 
'written permission.
'
'THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
'EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 
'OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT 
'SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 
'INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
'TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR 
'BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
'CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 
'ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH 
'DAMAGE.
'

Imports DotNetNuke.Services.Exceptions
Imports WillStrohl.Modules.QueryToGrid.QueryToGridController

Namespace WillStrohl.Modules.QueryToGrid

    Partial Public MustInherit Class ViewGrid
        Inherits WNSPortalModuleBase

#Region " Event Handlers "

        Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

            Try
                If DotNetNuke.Framework.AJAX.IsInstalled Then
                    DotNetNuke.Framework.AJAX.RegisterScriptManager()
                End If

                If Not Me.Page.IsPostBack Then
                    Me.BindData()
                End If

                Me.grdQuery.Visible = (Not Me.GetDataSource Is Nothing)

                Me.lblPageLoadTime.Text = DateTime.Now.ToString("hh:mm:ss tt")

                ' request that the DNN framework load the jQuery script into the markup
                DotNetNuke.Framework.jQuery.RequestRegistration()

            Catch exc As Exception ' Module failed to load
                ProcessModuleLoadException(Me, exc, Me.IsEditable)
            End Try

        End Sub

        Private Sub cmdSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdSubmit.Click

            Try

                If Not String.IsNullOrEmpty(Me.txtQuery.Text) Then
                    If Not Me.GetDataSource Is Nothing Then
                        Me.BindGridView()
                    Else
                        Me.lblMessage.Text = Me.GetLocalizedString("NoResults.Text")
                    End If
                Else
                    Me.lblMessage.Text = Me.GetLocalizedString("QueryError.Text")
                End If

            Catch exc As Exception ' Module failed to load
                ProcessModuleLoadException(Me, exc)
            End Try

        End Sub

        Private Sub grdQuery_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles grdQuery.PageIndexChanging

            Me.grdQuery.PageIndex = e.NewPageIndex
            Me.BindGridView()

        End Sub

        Private Sub grdQuery_Sorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs) Handles grdQuery.Sorting

            Me.BindGridView(e.SortExpression & " " & GetSortDirection(e.SortExpression))

        End Sub

#End Region

#Region " Helper Methods "

        Private Sub BindData()

            Me.LocalizeModule()

            If Me.GridSettings Is Nothing Then
                Me.grdQuery.PageSize = RECORDSPERPAGE_DEFAULT
            Else
                Me.grdQuery.PageSize = Me.GridSettings.RecordsPerPage
            End If

            Me.grdQuery.EmptyDataText = Me.GetLocalizedString("NoRecords.Text")

            Me.lblOriginalPageLoadTime.Text = DateTime.Now.ToString("hh:mm:ss tt")

        End Sub

        Private Overloads Sub BindGridView()
            Me.BindGridView(String.Empty)
        End Sub

        Private Overloads Sub BindGridView(ByVal SortExpression As String)

            Me.grdQuery.DataSource = Me.GetDataSource(SortExpression)
            Me.grdQuery.DataBind()

        End Sub

        Private Sub LocalizeModule()

            Me.lblQuery.Text = Me.GetLocalizedString("lblQuery.Text")
            Me.lblOriginalPageLoad.Text = Me.GetLocalizedString("lblOriginalPageLoad.Text")
            Me.lblPageLoad.Text = Me.GetLocalizedString("lblPageLoad.Text")
            Me.cmdSubmit.Text = Me.GetLocalizedString("cmdSubmit.Text")

            Me.lnkGridDefault.Text = Me.GetLocalizedString("lnkGridDefault.Text")
            Me.lnkGridPartialRendering.Text = Me.GetLocalizedString("lnkGridPartialRendering.Text")
            Me.lnkGridJQuery.Text = Me.GetLocalizedString("lnkGridJQuery.Text")
            Me.lnkTelerik.Text = Me.GetLocalizedString("lnkTelerik.Text")

        End Sub

        Private Sub lnkGridDefault_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkGridDefault.Click
            Me.SendTo(NavigateURL)
        End Sub

        Private Sub lnkGridJQuery_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkGridJQuery.Click
            Me.SendTo(EditUrl(Null.NullString, Null.NullString, "jQuery"))
        End Sub

        Private Sub lnkGridPartialRendering_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkGridPartialRendering.Click
            Me.SendTo(EditUrl(Null.NullString, Null.NullString, "Partial"))
        End Sub

        Private Sub lnkTelerik_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkTelerik.Click
            Me.SendTo(EditUrl(Null.NullString, Null.NullString, "Telerik"))
        End Sub

        Private Overloads Function GetDataSource() As DataTable
            Return GetDataSource(Null.NullString)
        End Function

        Private Overloads Function GetDataSource(ByVal SortExpression As String) As DataTable

            If Not String.IsNullOrEmpty(Me.txtQuery.Text) Then
                Dim dt As DataTable = Nothing
                Dim dr As IDataReader = DotNetNuke.Data.DataProvider.Instance().ExecuteSQL(Me.txtQuery.Text)

                If Not dr Is Nothing Then
                    dt = New DataTable
                    dt.Load(dr)

                    If Not String.IsNullOrEmpty(SortExpression) Then
                        dt.DefaultView.Sort = SortExpression
                    End If
                End If

                Return dt
            End If

            Return Nothing

        End Function

        Private Function GetSortDirection(ByVal column As String) As String

            ' By default, set the sort direction to ascending.
            Dim sortDirection As String = "ASC"

            ' Retrieve the last column that was sorted.
            Dim sortExpression As String = TryCast(ViewState("SortExpression"), String)

            If sortExpression IsNot Nothing Then
                ' Check if the same column is being sorted.
                ' Otherwise, the default value can be returned.
                If sortExpression = column Then
                    Dim lastDirection As String = TryCast(ViewState("SortDirection"), String)
                    If lastDirection IsNot Nothing AndAlso lastDirection = "ASC" Then
                        sortDirection = "DESC"
                    End If
                End If
            End If

            ' Save new values in ViewState.
            ViewState("SortDirection") = sortDirection
            ViewState("SortExpression") = column

            Return sortDirection

        End Function

#End Region

    End Class

End Namespace